<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <!-- 进度条 -->
      <el-progress v-if="showProgress" class="progress" :parcentage="parcentage" type="circle" :percentage="25" />
    </el-upload>
  </div>
</template>

<script>
// 导入 cos 模块
const COS = require('cos-js-sdk-v5')

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDA9sNbZFgrmQnukJbdQxEEm45pJWT8WdT',
  SecretKey: 'atwiESQ8ZjcDXaLq41h6D3cuwhAMHvIN'
})
export default {
  name: 'UploadImg',
  data() {
    return {
      imageUrl: '',
      showProgress: false, // 进度条显示变量
      parcentage: 0
    }
  },
  methods: {
    // 自定义上传属性
    upload(files) {
      if (files.file) {
        this.showProgress = true
        cos.putObject({
          Bucket: 'renzi-1308159419', /* 必须 */
          Region: 'ap-beijing', /* 存储桶所在地域，必须字段 */
          Key: files.file.name, /* 必须 */
          StorageClass: 'STANDARD',
          Body: files.file, // 上传文件对象
          onProgress: (progressData) => {
            this.parcentage = progressData.percent * 100
          }
        }, (err, data) => {
          if (err === null) {
            this.imageUrl = `https://${data.Location}`
          }
          this.showProgress = false
        })
      }
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 160px;
    height: 160px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .progress {
  position: absolute;
  display: flex;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #e4e4e4;
  border-radius: 50%;
  opacity: 0.9;
}
</style>
